<template>
  <div class="rg_layout">
    <div class="rg_left">
      <p>发布领养信息</p>
      <p>SEND PET ADOPT</p>
    </div>
    <div class="rg_center">
      <div class="rg_form">
        <div style="margin: 50px
        0;"></div>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item align="left">
            <el-upload
                ref="upload"
                list-type="picture-card"
                action='#'
                accept=".jpg, .png"
                :limit="1"
                :file-list="fileList"
                :auto-upload="false"
                :before-upload="beforeAvatarUpload"
                :on-change="HandleOnChange"
                :on-remove="HandleOnRemove"
                :on-exceed="handleOnExceed"
            >
              <el-button size="small" type="primary">选择宠物图片</el-button>

            </el-upload>
          </el-form-item>
          <el-form-item label="宠物姓名" prop="name">
            <el-col :span="20">
              <el-input placeholder="宠物姓名" v-model="form.name"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="宠物年龄" prop="age">
            <el-col :span="20">
              <el-input placeholder="请输入宠物的年龄" v-model="form.age"
                        oninput="value=value.replace(/\D/g,'')"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="宠物品种" prop="breed">
            <el-input placeholder="请输入宠物的品种" v-model="form.breed"></el-input>
          </el-form-item>
          <el-form-item label="宠物性别">
            <el-col :span="5">
              <el-radio v-model="form.radio" label="1">公</el-radio>
            </el-col>
            <el-col :span="3">
              <el-radio v-model="form.radio" label="2">母</el-radio>
            </el-col>
          </el-form-item>
          <el-form-item label="宠物介绍" prop="introduction">
            <el-col :span="20">
              <el-input type="textarea" placeholder="请输入宠物的年龄" v-model="form.introduction"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="联系地址" prop="address">
            <el-col :span="20">
              <el-input type="textarea" placeholder="请输入到时候用户需要到何处去领养" v-model="form.address"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="20">
              <el-button type="primary" @click="submitUpload">立即发布</el-button>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>

</template>

<script>
import axios from "axios";

export default {
  name: "signUp",
  data: function () {
    return {
      file: "",
      proofImage: '', //待上传文件base64编码
      fileList: [], //待上传文件列表
      form: {
        name: "",
        age: 0,
        breed: "",
        radio: '1',
        introduction: "",
        address: ""
      },
      rules: {
        name: [{required: true, message: '请输入宠物名字', trigger: 'blur'}],
        age: [{required: true, message: '请输入宠物年龄', trigger: 'blur'}],
        breed: [{required: true, message: '请输入品种', trigger: 'blur'}],
        introduction: [{required: true, message: '请输入介绍', trigger: 'blur'}],
        address: [{required: true, message: '请输入宠物地址', trigger: 'blur'}],
      },
      msg: ''
    }
  },
  methods: {
    open1() {
      this.$message({
        showClose: true,
        message: this.msg,
        type: 'warning'
      });
    },
    open2() {
      this.$message({
        showClose: true,
        message: this.msg,
        type: 'success'
      });
    },
    open3() {
      this.$message({
        showClose: true,
        message: this.msg,
        type: 'error'
      });
    },
    submitUpload() {
      this.onSubmit();
    },
    onSubmit() {
      let str = this.proofImage.split("base64,")[1];
      if(this.$store.state.userId==0){
        alert("请去登陆");
        this.$router.replace({path: '/login'});
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          let _this = this;
          let tmp;
          if (this.form.radio === "1") {
            tmp = '公'
          } else {
            tmp = '母'
          }
          axios.post(this.$store.state.url+":8412/pet/insertPetData",
              {
                address: this.form.address,
                age: this.form.age,
                breed: this.form.breed,
                introduction: this.form.introduction,
                name: this.form.name,
                sex: tmp,
                userId: localStorage.getItem("myId"),
                picture:str
              }
          ).catch(function (error) {
            _this.msg = "请插入图片！！！";
            _this.open1()
          }).then(function (response) {
            if (response.data.code === 200) {
              _this.msg = response.data.msg
              _this.open2()
              _this.$router.replace({path: '/index'});
            } else {
              _this.msg = response.data.msg
              _this.open3()
            }
          })
        }
      })
    },

    beforeAvatarUpload(file) {
      const fileType = file.type === 'image/jpeg' || file.type === 'image/png'
      const result = file.size / 1024 / 1024 < 1;
      if (!fileType) {
        this.$message.error("上传图片只能是 JPG和png 格式!");
        return false;
      }
      if (!result) {
        this.$message.error("上传图片大小不能超过 1M");
        return false;
      }
    },

    //文件列表移除文件时
    HandleOnRemove() {
      this.proofImage = '' //清空待上传文件base64编码
    },

    //文件超出个数限制时
    handleOnExceed() {
      this.$message.error("只能上传一张！");
    },

    //获得待传文件base64编码
    HandleOnChange(file) {
      this.getBase64(file.raw).then(res => {
        this.proofImage = res
      })
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },

    //将根据base64转码后的str进行访问
    MyRequest() {
      let str = this.proofImage.split("base64,")[1];
      console.log(str);
      axios.post(this.$store.state.url+":8412/pet/pushToGitee",
          {
            content: str
          }).then(res => {
        if (res) {
          this.$message.success("图片上传成功！");
          this.proofImage = '' //清空待上传文件base64编码
          this.fileList = [] //清空上传列表
        }
      })
    },
  }
}
</script>


<style>
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

.rg_layout {
  width: 900px;
  min-height: 650px;
  border: 5px solid #EEEEEE;
  background-color: white;
  opacity: 0.8;
  /*让div水平居中*/
  margin: auto;
  margin-top: 15px;
}

.rg_left {
  float: left;
  margin: 15px;
  width: 20%;
}

.rg_left > p:first-child {
  color: #FFD026;
  font-size: 20px;
}

.rg_left > p:last-child {
  color: #A6A6A6;
}

.rg_center {
  /*border: 1px solid red;*/
  float: left;
  width: 450px;
  /*margin: 15px;*/
}

.rg_right {
  float: right;
  margin: 15px;
}

.rg_right > p:first-child {
  font-size: 15px;
}

.rg_right p a {
  color: pink;
}


</style>
